<template>
  <div class="nickName-container">
    <!-- 导航栏 -->
    <van-nav-bar title="设置昵称"
      left-text="取消"
      right-text="确定"
      @click-left="$emit('close')"
      @click-right="onUpdateNickName" />
    <!-- /导航栏 -->
    <div class="field-wrap">
      <van-field v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入新昵称"
        show-word-limit />
    </div>
  </div>
</template>

<script>
import { editUserProfile } from '@/api/user'
export default {
  name: 'NickName',
  components: {},
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      localName: this.value
    }
  },

  methods: {
    async onUpdateNickName () {
      // 如果网速较慢或其他原因 请求等待的过程中 添加loading提示
      // 开启loading  当提示成功或失败的时候会自动关闭Loading
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })

      try {
        // 数据为空的清空下弹框提示
        if (this.localName.length === 0) {
          this.$toast('昵称不能为空')
          return
        }
        await editUserProfile({ name: this.localName })
        // 关闭弹层
        this.$emit('close')
        // 更新视图
        this.$emit('input', this.localName)
        // 提示成功
        this.$toast.success('更新成功')
      } catch (err) {
        // 提示失败
        this.$toast.fail('修改昵称失败，请重试')
      }
    }
  }
}
</script>

<style scoped lang="less">
.field-wrap {
  padding: 20px;
}
</style>
